package cn.jufuns.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class JSONUtil {
private static Log log = LogFactory.getLog(JSONUtil.class);
	
	/**
	 * json的string转bean
	 * @param jsonArrStr
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public static List toList(String jsonArrStr,Class clazz) throws Exception{
		
		List resultList = new ArrayList();
		
		//先读取串数组		
		 JSONArray array = JSONArray.fromObject(jsonArrStr);
		 //转成对像数组
		 Object[] objectArr = array.toArray();                
		 
		 //再使用JsonObject遍历一个个的对像
		 for(int i = 0; i < objectArr.length; i++){
			 
			 Object vo = clazz.newInstance();
			 
			 JSONObject jsonObject = JSONObject.fromObject(objectArr[i]);
			 //指定转换的类型，但仍需要强制转化-成功
			 vo = jsonObject.toBean(jsonObject,clazz);
			 
			 resultList.add(vo);
		 }
		 
		 return resultList;
	}
	public static Object toBean(String jsonArrStr,Class clazz) throws Exception{
		
		Object vo = clazz.newInstance();

		JSONObject jsonObject = JSONObject.fromObject(jsonArrStr);
		//指定转换的类型，但仍需要强制转化-成功
		vo = jsonObject.toBean(jsonObject,clazz);
			
		
		return vo;
	}
	public static Object toBean(String jsonArrStr,Class clazz,Map<String, Class> classMap) throws Exception{
		
		Object vo = clazz.newInstance();
		
		JSONObject jsonObject = JSONObject.fromObject(jsonArrStr);
		//指定转换的类型，但仍需要强制转化-成功
		vo = jsonObject.toBean(jsonObject,clazz,classMap);
		
		
		return vo;
	}
}
